<?php
/**
 * 数据库类
 *
 */
class core_db {

	private $conn = null;

	/**
	 * 连接数据库
	 *
	 * @param array $dsn
	 * @return boolean
	 */
	function connect($dsn = false) {
		if ($dsn==false) { return false; }
		if(isset($dsn['port']) && $dsn['port']!='') {
            $host = $dsn['host'] . ':' . $dsn['port'];
		} else {
			$host = $dsn['host'];
		}
		$this->conn = mysql_connect($host, $dsn['username'], $dsn['password']);
		if (!$this->conn) {
			return 'ERROR:' . mysql_error();
		}
		if (!empty($dsn['database'])) {
	        if (!$this->selectDb($dsn['database'])) { return false; }
	    }
        if (!empty($dsn['charset'])) {
            $this->query('SET NAMES ' . $dsn['charset']);
        }
        unset($dsn);
	    return true;
	}

	/**
	 * 关闭数据库连接
	 */
	function close() {
		if ($this->conn) { mysql_close($this->conn); }
        $this->conn = null;
	}

	/**
	 * 选择要操作的数据库
	 *
	 * @param string $database
	 * @return boolean
	 */
	private function selectDb($database) {
		if(!mysql_select_db($database,$this->conn)){ return false; }
		return true;
	}

	/**
	 * 执行一个查询，返回一个 resource 或者 boolean 值
	 *
	 * @param string $sql
	 * @param boolean $unbuffer
	 * @return resource/boolean
	 */
	function query($sql, $unbuffer = false) {
		return function_exists('mysql_unbuffered_query') && $unbuffer ? mysql_unbuffered_query($sql) : mysql_query($sql);
	}

    function fetchRow($res)
    {
        return mysql_fetch_row($res);
    }

    function fetchAssoc($res)
    {
        return mysql_fetch_assoc($res);
    }

    function freeRes($res)
    {
        return mysql_free_result($res);
    }

    /**
     * 获得元数据
     *
     * @param string $table
     * @return array
     */
    function getMetas($table) {
    	$res = $this->query("SHOW FULL COLUMNS FROM `{$table}`");
		$metas = array();
		while (($row = $this->fetchRow($res))) {
		   $metas[] = reset($row);
		}
		$this->freeRes($res);
		return $metas;
    }

}